<template>
  <div class="video-upload">
    <div v-if="!uploading" class="upload-trigger" @click="triggerUpload">
      <input
        ref="fileInput"
        type="file"
        accept="video/*"
        style="display: none"
        @change="handleFileChange"
      />
      <van-icon name="plus" size="24" />
      <span>上传视频</span>
    </div>
    <div v-else class="upload-progress">
      <div class="progress-info">
        <span>{{ statusText }}</span>
        <span>{{ authProgress }}%</span>
      </div>
      <van-progress :percentage="authProgress" :show-pivot="false" />
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { showToast } from 'vant'
import { videoApi } from '@/api/video'

const props = defineProps({
  maxSize: {
    type: Number,
    default: 1024 * 1024 * 500, // 默认500MB
  },
  formData: {
    type: Object,
    default: () => ({}),
  },
})

const emit = defineEmits(['success', 'error'])

const fileInput = ref(null)
const uploader = ref(null)
const file = ref(null)
const uploading = ref(false)
const authProgress = ref(0)
const statusText = ref('准备上传...')

const triggerUpload = () => {
  fileInput.value.click()
}

const handleFileChange = async (event) => {
  file.value = event.target.files[0]
  if (!file.value) return

  if (file.value.size > props.maxSize) {
    showToast(`文件大小不能超过${props.maxSize / 1024 / 1024}MB`)
    return
  }
  uploader.value = createUploader()
  uploader.value.addFile(file.value)
  uploader.value.startUpload()
}

const createUploader = () => {
  const uploaderInstance = new AliyunUpload.Vod({
    timeout: 60000,
    partSize: 1048576,
    parallel: 5,
    retryCount: 3,
    retryDuration: 2,
    region: 'cn-shanghai',
    userId: '1040322081948813',
    localCheckpoint: true,
    addFileSuccess: () => {
      statusText.value = '添加文件成功, 等待上传...'
      uploading.value = true
    },
    onUploadstarted: async (uploadInfo) => {
      if (!uploadInfo.videoId) {
        try {
          const res = await videoApi.getUploadAuth({
            title: props.formData.title.trim(),
            description: props.formData.description.trim(),
            fileName: uploadInfo.file.name,
          })
          const { VideoId, UploadAuth, UploadAddress } = res
          uploaderInstance.setUploadAuthAndAddress(uploadInfo, UploadAuth, UploadAddress, VideoId)
        } catch (error) {
          showToast('上传失败：' + error.message)
        }
      } else {
        try {
          const res = await videoApi.refreshUploadAuth(uploadInfo.videoId)
          console.log(res)
          const { VideoId, UploadAuth, UploadAddress } = res
          uploaderInstance.setUploadAuthAndAddress(uploadInfo, UploadAuth, UploadAddress, VideoId)
        } catch (error) {
          console.log(error)
        }
      }
      statusText.value = '文件开始上传...'
    },
    onUploadSucceed: (uploadInfo) => {
      statusText.value = '文件上传成功!'
      console.log(uploadInfo)
      emit('success', uploadInfo)
    },
    onUploadFailed: (uploadInfo, code, message) => {
      statusText.value = '文件上传失败!'
      emit('error', { code, message })
    },
    onUploadProgress: (uploadInfo, totalSize, progress) => {
      authProgress.value = Math.ceil(progress * 100)
      statusText.value = '文件上传中...'
    },
    onUploadTokenExpired: (uploadInfo) => {
      statusText.value = '文件超时...'
    },
    onUploadEnd: (uploadInfo) => {
      statusText.value = '文件上传完毕'
    },
  })
  return uploaderInstance
}
</script>

<style scoped>
.video-upload {
  width: 100%;
  padding: 16px;
}

.upload-trigger {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 120px;
  background-color: #f7f8fa;
  border-radius: 8px;
  cursor: pointer;
}

.upload-trigger span {
  margin-top: 8px;
  font-size: 14px;
  color: #666;
}

.upload-progress {
  padding: 16px 0;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}
</style>
